package com.machine.filling.net.http.network;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.google.gson.Gson;
import com.machine.filling.MyApp;
import com.machine.filling.net.http.response.BaseHttpResponseBean;
import com.machine.filling.util.LogUtils;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * Created by sperfan on 2018/3/1.
 *
 * @描述:
 */
@Deprecated
public abstract class BaseHttpStringCallback2 implements Callback, IhttpCallback2 {
    private static final String TAG = "BaseHttpStringCallback";

    public static final String ERROR_REQUEST = "onError";//请求异常

    public static final String ERROR_RESPONSE = "response_exceptiono";//结果返回处理异常


    @Override
    public void onFailure(Call call, IOException e) {
        if (!MyApp.errorRequests.contains(call.request())) {
            Log.d(TAG, "异常请求提交: " + "提交失败");
            MyApp.errorRequests.add(call.request());
        } else {
            Log.d(TAG, "异常请求提交: " + "再次失败" + call.request().body());
        }

        Message msg = Message.obtain();
        msg.what = 1;
        msg.obj = e;

        Buffer buffer = new Buffer();
        try {
            call.request().body().writeTo(buffer);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        Charset charset = Charset.forName("utf-8");
        String paramsStr = buffer.readString(charset);
        Bundle bundle = new Bundle();
        bundle.putSerializable("requestParams",paramsStr);
        msg.setData(bundle);

        mHandler.sendMessage(msg);
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if (MyApp.errorRequests.contains(call.request())) {
            Log.d(TAG, "异常请求提交: " + "这是老的request,已经删除");
            MyApp.errorRequests.remove(call.request());
        } else {
            Log.d(TAG, "异-常请求提交: " + "新的request已经通过");
        }

        Message msg = Message.obtain();
        msg.what = 0;
        msg.obj = response.body().string();

        Buffer buffer = new Buffer();
        try {
            call.request().body().writeTo(buffer);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        Charset charset = Charset.forName("utf-8");
        String paramsStr = buffer.readString(charset);
        Bundle bundle = new Bundle();
        bundle.putSerializable("requestParams",paramsStr);
        msg.setData(bundle);

        mHandler.sendMessage(msg);
    }

    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    String responseStr = (String) msg.obj;
                    BaseHttpResponseBean baseHttpResponseBean = null;
                    String requestStr0 = msg.getData().getString("requestParams");
                    try {
                        LogUtils.d(TAG, "返回结果：====" + responseStr);
                        baseHttpResponseBean = new Gson().fromJson(responseStr, BaseHttpResponseBean.class);
                    } catch (Exception e) {
                        // TODO: 2018/4/13 0013 异常分门别类, 进行统一处理
                        onFailed(ERROR_RESPONSE, e.toString(), e,requestStr0);
                        LogUtils.e(TAG, "返回结果：请求失败onResponse===" + e.toString());
                        onFinished();
                    }
                    if (baseHttpResponseBean == null) {
                        Log.d(TAG, "handleMessage() returned: 数据解析异常");
                        onFailed(ERROR_REQUEST, "基本数据，解析异常", new RuntimeException("基本数据，解析异常"),requestStr0);
                    } else {
                        if (baseHttpResponseBean.isCode0000()) {
                            onSuccess(null, responseStr);
                        } else {
                            onFailed(baseHttpResponseBean.getCode(), baseHttpResponseBean.getMsg(), null,requestStr0);
                        }
                    }
                    onFinished();
                    break;

                case 1:
                    Exception e = (Exception) msg.obj;
                    Bundle bundle = msg.getData();
                    String requestStr1 = bundle.getString("requestStr");
                    if (e instanceof SocketTimeoutException) {
                        onFailed(ERROR_REQUEST, "网络异常!", e,requestStr1);
                    } else if (e instanceof UnknownHostException) {
                        onFailed(ERROR_REQUEST, "网络异常", e,requestStr1);
                    } else {
                        onFailed(ERROR_REQUEST, e.toString(), e,requestStr1);
                    }
                    LogUtils.e(TAG, "返回结果：请求失败onError===" + e.toString());
                    onFinished();
                    break;
            }
        }
    };

}
